<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <el-dialog v-model="props.importVisible" class="add_regional_library" title="上传文件" width="600px" @close="handleVisible('cancel')">
    <el-upload
      action="#"
      :file-list="fileList"
      :multiple="false"
      :show-file-list="true"
      :auto-upload="false"
      :limit="1"
      :before-upload="beforeUpload"
      :on-change="handleChange"
      :on-remove="handleRemove"
      accept=".xls,.xlsx"
      align="center"
    >
      <div class="upload-area">
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text" style="text-align: center">
          点击上传<br />
          仅支持上传.xls或.xlsx格式的文件<br />
        </div>
      </div>
    </el-upload>
    <!-- <div align="center"><el-link type="primary" @click="download">模板下载</el-link></div> -->

    <template #footer>
      <div class="dialog-footer">
        <el-button size="small" @click="handleVisible('cancel')">取消</el-button>
        <el-button size="small" type="primary" @click="confirm"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="TabsModel">
import { downloadFile } from '@/utils/index';
import { importData, downloadTemplate } from '@/api/fastenerData';
const props = defineProps(['importVisible']);
const emit = defineEmits(['handleEvent']);
const fileList = ref([]);
// 下载模板
const download = () => {
  downloadTemplate().then((res) => {
    downloadFile(res, `许用值导入模板`, 'xlsx');
  });
};
// 验证文件大小是否正确
const beforeUpload = (file) => {
  const isLt = file.size / 1024 / 1024 < 100;
  if (!isLt) {
    ElMessage.error(`导入文件太大`);
    return false;
  }
  return true;
};
const handleRemove = (file, files) => {
  fileList.value = files;
};
const handleChange = (file, files) => {
  fileList.value = files;
};
const handleVisible = (type) => {
  if (type === 'cancel') {
    emit('handleEvent', { type: 'close' });
  } else {
    emit('handleEvent', { type: 'refresh' });
  }
};
const confirm = () => {
  if (fileList.value.length === 0) {
    ElMessage.warning(`请先选择上传文件`);
    return;
  }
  const file = fileList.value[0].raw;
  const formData = new FormData();
  formData.append('file', file);
  importData(formData).then((res) => {
    if (res.code === 200) {
      ElMessage.success(`导入成功`);
      handleVisible();
    } else {
      ElMessage.error(`导入失败，${res.msg}`);
    }
  });
};
</script>
<style lang="scss" scoped>
.add_regional_library {
  .upload-area {
    text-align: center;
    border: 2px dashed #ccc;
    padding: 20px;
  }
  .dialog-footer {
    display: flex;
    justify-content: center;
  }
}
</style>
